// tspcluster - Traveling Salesman Problem
// Copyright (C) 2006  Frederik Carlier
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace UGent.Tsp
{
    /// <summary>
    /// Exposes methods to do least squares fitting.
    /// </summary>
    class LeastSquares
    {
        /// <summary>
        /// Fits a polynom y = f(x) of degree n to a set of points.
        /// </summary>
        /// <param name="x">The values of x</param>
        /// <param name="y">The values of y</param>
        /// <param name="n">The degree of the polynom</param>
        public static double[] Fit(double[] x, double[] y, int n)
        {
            if (n < 0)
                throw new ArgumentOutOfRangeException("n");

            if (x == null)
                throw new ArgumentNullException("x");

            if (y == null)
                throw new ArgumentNullException("y");

            if (x.Length != y.Length)
                throw new ArgumentException("Both x and y must have the same length");

            int length = x.Length;

            // Solve the equation AX = B;
            // X containing the coefficients of the powers of X;
            // A being the values of the powers of X (or any other
            // variable).
            // See http://en.wikipedia.org/wiki/Linear_least_squares#Example

            // Let the matrix A contain the the values of the power of x (hence, x^0 == 1);
            // Let the matrix B contain the values f(x)

            double[,] A = new double[length, n + 1];
            double[] B = new double[length];
            for (int i = 0; i < length; i++)
            {
                B[i] = y[i];

                for (int j = 0; j <= n; j++)
                {
                    A[i, j] = Math.Pow(x[i], (double)(j));
                }
            }

            /*
            QR decomposition = new QR(A);
            Vector X = decomposition.Solve(B);

            return X.ToArray();
            */
            
            throw new NotImplementedException();
        }
    }
}
